import asyncio
from datetime import datetime
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from pytz import timezone
from .collectors.eastmoney import EastMoneyCollector
from .services.bond_service import BondService
from .utils.logger import get_logger
from .utils.config import config

logger = get_logger(__name__)

class TaskScheduler:
    """任务调度器"""

    def __init__(self):
        self.scheduler = AsyncIOScheduler()
        self.collector = EastMoneyCollector()
        self.bond_service = BondService()
        self.tz = timezone(config.get('scheduler.timezone', 'Asia/Shanghai'))

    def start(self):
        """启动调度器"""
        try:
            # 添加数据爬取任务
            self.scheduler.add_job(
                self.crawl_data,
                CronTrigger(
                    minute=f"*/{config.get('scheduler.check_interval', '30')}",
                    timezone=self.tz
                ),
                name='crawl_data'
            )

            # 添加申购提醒任务
            self.scheduler.add_job(
                self.check_and_notify,
                CronTrigger(
                    hour='10',
                    minute='0',
                    timezone=self.tz
                ),
                name='check_and_notify'
            )

            # 启动调度器
            self.scheduler.start()
            logger.info("Scheduler started successfully")

            # 保持程序运行
            asyncio.get_event_loop().run_forever()

        except Exception as e:
            logger.error(f"Error starting scheduler: {e}")
            raise

    async def crawl_data(self):
        """爬取数据任务"""
        try:
            logger.info("Starting data collection")
            await self.collector.collect()
            logger.info("Data collection completed")
        except Exception as e:
            logger.error(f"Error in data collection task: {e}")

    def check_and_notify(self):
        """检查并发送通知任务"""
        try:
            logger.info("Starting bond check and notification")
            self.bond_service.check_and_notify()
            logger.info("Bond check and notification completed")
        except Exception as e:
            logger.error(f"Error in bond check and notification task: {e}")

def run():
    """运行调度器"""
    scheduler = TaskScheduler()
    scheduler.start() 